package com.housekeeper.maili.housekeeper.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by macma on 2017/8/8.
 */

public class AppUtils {
    public static Toast toast;
    private static JSONObject jsonCity;

    /**
     * SharedPreferences 保存在手机里面的文件名
     */
    private static final String FILE_NAME = "share_date";
    private static Gson gson;

    /**
     * 吐司
     *
     * @param context
     * @param msg
     */
    public static void toast(Context context, String msg) {
        if (TextUtils.isEmpty(msg)) return;
        if (toast == null) {
            toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }

    public static Gson getgson() {
        if (gson == null) {
            gson = new Gson();
        }
        return gson;
    }

    /**
     * 判断网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {

        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (null != connectivity) {

            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (null != info && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void displayImage(Context context, final ImageView view, String url) {
        if (TextUtils.isEmpty(url)) {
            AppUtils.toast(context, "网址为空");
            return;
        }
//        Picasso.with(context)
//                .load(url)
//                .fit()
//                .into(view);

    }

    public static void displayImageGlide(Context context, final ImageView view, String url) {
        if (TextUtils.isEmpty(url)) {
            AppUtils.toast(context, "网址为空");
            return;
        }
//        Picasso.with(context)
//                .load(url)
//                .fit()
//                .into(view);
        Glide.with(context).load(url).into(view);
    }


    /**
     * 数据加载
     *
     * @param context 上下文
     * @return AlertDialog对象
     */
//    public static AlertDialog getDialog(Context context) {
//        AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.loading_dialog);//设置AlertDialog样式
//        View v = View.inflate(context, R.layout.layout_spinkitview, null);
//        ProgressBar bar = (ProgressBar) v.findViewById(R.id.spin_kit);
//        DoubleBounce doubleBounce = new DoubleBounce();
//        bar.setIndeterminateDrawable(doubleBounce);
//        builder.setView(v);
//        AlertDialog dialog = builder.create();
//        dialog.setCanceledOnTouchOutside(false);
//        return dialog;
//    }

    /**
     * 验证是否是电话号码
     *
     * @param mobiles 需要验证的号码
     * @return 是否是电话号码
     */
    public static boolean isMobileNO(String mobiles) {
        String telRegex = "[1][34578]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    /**
     * 验证是否是邮箱
     *
     * @param email 需要验证的号码
     * @return 是否是邮箱
     */
    public static boolean isEmail(String email) {
        if (null == email || "".equals(email)) return false;
        //Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配
        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * 显示键盘
     *
     * @param acticvity
     */
    public static void showinput(Activity acticvity) {
        if (!(acticvity.getWindow().getAttributes().softInputMode ==
                WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)) {
            ((InputMethodManager) acticvity.getSystemService(acticvity.INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 隐藏键盘
     *
     * @param acticvity
     */
    public static void hideinput(Activity acticvity) {

//        if ((acticvity.getWindow().getAttributes().softInputMode ==
//                WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)) {
//            acticvity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
//        }
        ((InputMethodManager) acticvity.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(acticvity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//        ((InputMethodManager) acticvity.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(acticvity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 自带的数据加载
     */
    public static ProgressDialog getProgressDialog(Context context, String msg) {
        ProgressDialog dialog = new ProgressDialog(context);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条
//        dialog.setTitle("提示");//设置标题
//        dialog.setIcon(R.drawable.icon);//设置图标
        dialog.setIndeterminate(false);//设置进度条是否为不明确
        dialog.setCancelable(true);//设置进度条是否可以按退回键取消
        dialog.setMessage(msg);//设置消息
        dialog.setCanceledOnTouchOutside(false);//设置点击进度对话框外的区域对话框不消失
        return dialog;
    }

    /**
     * 返回一个一定值内的随机数
     *
     * @param i 定值
     * @return
     */
    public static int getint(int i) {
        Random ran = new Random();
        return ran.nextInt(i);
    }

    /**
     * 时间转换为时间戳
     *
     * @param timeStr 时间 例如: 2016-03-09
     * @param format  时间对应格式  例如: yyyy-MM-dd  yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static long getTimeStamp(String timeStr, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = simpleDateFormat.parse(timeStr);
            long timeStamp = date.getTime();
            return timeStamp;
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("-------------------" + e.toString());
        }
        return 0;
    }

    public static long getTime(String user_time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d;
        try {
            d = sdf.parse(user_time);
            long l = d.getTime();
            return l;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 指定时间格式
     *
     * @param time
     * @param DateForma
     * @return
     */
    public static String getDate(long time, String DateForma) {
        if (DateForma == null || DateForma.equals(""))
            DateForma = "yyyy-MM-dd  HH:mm";
        SimpleDateFormat format = new SimpleDateFormat(DateForma);
        return format.format(new Date(time * 1000));
    }

    public static String getDateAndMinute(long time) {
        SimpleDateFormat format = new SimpleDateFormat("MM/dd - HH:mm");
        return format.format(new Date(time * 1000));
    }

    /**
     * 隐藏手机号中间4位
     *
     * @param phone 需要隐藏的手机号
     * @return
     */
    public static String getphone(String phone) {
        if (isMobileNO(phone)) {

            String newphone = "";
            newphone = phone.substring(0, 3) + "****";
            newphone += phone.substring(7, 11);
            return newphone;
        }
        return "该手机号格式错误";
    }

    /**
     * 获取所有的非系统app的名字
     *
     * @param context
     * @return
     */
    //
    public static List<String> getAllAppName(Context context) {
        List<String> appList = new ArrayList<>();
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);

        for (int i = 0; i < packages.size(); i++) {
            PackageInfo packageInfo = packages.get(i);
            packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString();
            String packageName = packageInfo.packageName;
//            packageInfo.versionCode;//版本号
//            packageInfo.versionName;//版本名称
//            packageInfo.applicationInfo.loadIcon(context.getPackageManager());
            //判断是否系统应用
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                //非系统应用
                appList.add(packageName);
            } else {
                //系统应用
            }
        }
        return appList;
    }


    /**
     * 打开指定包名的应用
     *
     * @param packageName
     * @param context
     */
    public static void openCLD(String packageName, Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo pi = null;

        try {
            pi = packageManager.getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {

        }
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(pi.packageName);

        List<ResolveInfo> apps = packageManager.queryIntentActivities(resolveIntent, 0);

        ResolveInfo ri = apps.iterator().next();
        if (ri != null) {
            String className = ri.activityInfo.name;
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            ComponentName cn = new ComponentName(packageName, className);

            intent.setComponent(cn);
            context.startActivity(intent);
        }
    }

    /**
     * 设置粘贴版内容
     *
     * @param context
     * @param content
     */
    public static void setCopyContent(Context context, String content) {
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content.trim());
    }

    /**
     * 写入sd卡
     *
     * @param key
     * @param vl
     */
    public static void out(String key, String vl) {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Artifact";
        File file = new File(path);
        if (!file.isFile()) {
            file.mkdirs();
        }
        try {
            OutputStream out = new FileOutputStream(file.getPath() + "/message", true);
            PrintStream ps = new PrintStream(out);
            Class<?> clazz = Class.forName("android.os.Build");
            Field[] fields = clazz.getFields();
            for (Field field : fields) {
                ps.println(field.getName() + " : " + field.get(null));
            }
            ps.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
            ps.println(key + ":" + vl);
            ps.println("===================================分割线===================================");
            ps.println();
            ps.println();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        Process.killProcess(Process.myPid());
    }

    /**
     * 获得全角字符串 避免自动换行右边不对起
     *
     * @param input
     * @return
     */
    public static String getAligningString(String input) {
        if (TextUtils.isEmpty(input)) {
            return "";
        }
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    /**
     * 判断是否是正确的省份证号码
     * * @param cid
     *
     * @return
     */
    public static boolean isRightForID(String cid) {
        if (!cid.matches("^\\d{17}(\\d|x|X)$")) {
            return false;
        }
        String aCity = "{'11':'北京','12':'天津','13':'河北','14':'山西','15':'内蒙古','21':'辽宁','22':'吉林','23':'黑龙江','31':'上海','32':'江苏','33':'浙江','34':'安徽','35':'福建','36':'江西','37':'山东','41':'河南','42':'湖北',"
                + "'43':'湖南','44':'广东','45':'广西','46':'海南','50':'重庆','51':'四川','52':'贵州','53':'云南','54':'西藏','61':'陕西','62':'甘肃','63':'青海','64':'宁夏','65':'新疆','71':'台湾','81':'香港','82':'澳门','91':'国外'}";
        if (jsonCity == null) {
            try {
                jsonCity = new JSONObject(aCity);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        int[] arrExp = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5,
                8, 4, 2};// 加权因子
        Object[] arrValid = new Object[]{1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2};// 校验码
        int iSum = 0, idx;
        String sBirthday = cid.substring(6, 10) + "-"
                + Integer.parseInt(cid.substring(10, 12)) + "-"
                + Integer.parseInt(cid.substring(12, 14));

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date d = df.parse(sBirthday);
            calendar.setTime(d);
        } catch (ParseException e1) {
            e1.printStackTrace();
        }

        try {
            Log.i("fengzi", ";js" + jsonCity + "");
            if (jsonCity.get(cid.substring(0, 2)) == null) {
                return false;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (!sBirthday.equals((calendar.get(Calendar.YEAR) + "-"
                + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar
                .get(Calendar.DAY_OF_MONTH)))) {
            return false;
        }
        for (int i = 0; i < cid.length() - 1; i++) {
            // 对前17位数字与权值乘积求和
            iSum += Integer.parseInt(cid.substring(i, i + 1), 10) * arrExp[i];
        }
        // 计算模（固定算法）
        idx = iSum % 11;
        // 检验第18为是否与校验码相等
        return cid.substring(17, 18).toUpperCase().equals(arrValid[idx] + "");
    }

    /**
     * 时间戳转换成日期格式字符串
     *
     * @return
     * @paramseconds精确到秒的字符串
     * @paramformatStr
     */
    public static String timeStamp2Date(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (format == null || format.isEmpty()) format = "yyyy-MM-dd  HH:m";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds + "000")));
    }


    /**
     * 去xml里面标签
     *
     * @param msg
     * @return
     */
    public static StringBuffer getStringfoXML(String msg) {
        StringBuffer ssss = new StringBuffer();
        String[] split = msg.split(">");
        for (int k = 0; k < split.length; k++) {
            if (!split[k].startsWith("<")) {
                int end = split[k].indexOf("<");
                String substring = "";
                if (end == -1) {
                    substring = split[k];
                } else {
                    substring = split[k].substring(0, end);
                }
                ssss.append(substring);
            }
//                    LogUtils.i_fengzi(k+"修改后：" + ssss.toString());
        }
//                    LogUtils.i_fengzi("修改后：" + ssss.toString());
        return ssss;
    }

    /**
     * 添加下划线
     *
     * @param tvTest
     */
    public static void setp(TextView tvTest) {
        tvTest.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        tvTest.getPaint().setAntiAlias(true);//抗锯齿
    }

    /**
     * 判断当前日期是星期几
     *
     * @param pTime 时间戳
     * @return dayForWeek 判断结果
     * @Exception 发生异常
     */

//  String pTime = "2012-03-12";
    public static String getWeek(String pTime) {

        String Week = "星期";
        String date = timeStamp2Date(pTime, "yyyy-MM-dd");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try {

            c.setTime(format.parse(date));

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            Week += "天";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
            Week += "一";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) {
            Week += "二";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) {
            Week += "三";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
            Week += "四";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
            Week += "五";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
            Week += "六";
        }

        return Week;
    }

    /**
     * unicode转utf-8
     */
    public static String decode(String unicodeStr) {
        byte[] converttoBytes = new byte[0];
        String s2 = "tttt";
        try {
            converttoBytes = unicodeStr.getBytes("UTF-8");
            s2 = new String(converttoBytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return s2;
    }

    /**
     * 判断是否是网址
     *
     * @param url
     * @return
     */
    public static boolean isUrl1(String url) {
        Pattern pattern = Pattern
                .compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://|[Rr][Tt][Ss][Pp]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");
        return pattern.matcher(url).matches();
    }

    /**
     * 服务是否运行
     *
     * @param context
     * @param serviceName
     * @return
     */
    public static boolean isServiceRunning(Context context, String serviceName) {
        boolean isRunning = false;
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> lists = am.getRunningServices(30);
        for (ActivityManager.RunningServiceInfo info : lists) {// 获取运行服务再启动
//            LogUtils.i_fengzi("name--->" + info.service.getClassName());
            if (info.service.getClassName().equals(serviceName)) {
                isRunning = true;
            }
        }
        return isRunning;

    }

    /**
     * 手机唯一识别码
     */
//    public static String getsimi(Context context) {
//        TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
//        String szImei = TelephonyMgr.getDeviceId();//1、获取手机唯一识别码
//        //2、1无法获取获取2的识别码
//        if (TextUtils.isEmpty(szImei) || szImei.length() != 15) {
//            szImei = "35" +
//                    Build.BOARD.length() % 10 +
//                    Build.BRAND.length() % 10 +
//                    Build.CPU_ABI.length() % 10 +
//                    Build.DEVICE.length() % 10 +
//                    Build.DISPLAY.length() % 10 +
//                    Build.HOST.length() % 10 +
//                    Build.ID.length() % 10 +
//                    Build.MANUFACTURER.length() % 10 +
//                    Build.MODEL.length() % 10 +
//                    Build.PRODUCT.length() % 10 +
//                    Build.TAGS.length() % 10 +
//                    Build.TYPE.length() % 10 +
//                    Build.USER.length() % 10; //13 digits
//            //3、1和2都无法获取产生随机数
//            if (TextUtils.isEmpty(szImei) || szImei.length() != 15) {
//                szImei = AppUtil.getsp(context, "szImei", "");
//                if (TextUtils.isEmpty(szImei) || szImei.length() != 15) {
//                    for (int i = 0; i < 15; i++) {
//                        szImei += srr.charAt(AppUtil.getint(srr.length()));
//                    }
//                    AppUtil.savesp(context, "szImei", szImei);
//                }
//            }
//        }
//        //MD5加密
//        return MD5Util.encrypt(szImei);
//    }

}
